import axios from 'axios'

import { bwUtilsCookie } from '@/utils'
import { Modal } from 'ant-design-vue'
import { AxiosCanceler } from './http/axiosCancel'
import { checkStatus } from './http/checkStatus'
import { AxiosRetry } from './http/axiosRetry'

import { BwCacheEnum } from '@/enums/cacheEnum'
import { RequestEnum, ContentTypeEnum } from './enum'

import type { AxiosInstance, AxiosResponse } from 'axios'
const axiosInstance: AxiosInstance = axios.create({
  // authenticationScheme: '',
  // timeout: 10 * 1000,
  timeout: -1,

  headers: { 'Content-Type': ContentTypeEnum.JSON },
  // // 如果是form-data格式
  // // headers: { 'Content-Type': ContentTypeEnum.FORM_URLENCODED },
  // // 数据处理方式
  // transform: {
  //   beforeRequestHook:,
  // },
})

const axiosCanceler = new AxiosCanceler()

// Request interceptor configuration processing
axiosInstance.interceptors.request.use((config: any) => {
  const accessToken = bwUtilsCookie.getCookie(BwCacheEnum.token)
  if (accessToken) {
    ;(config as Record<string, any>).headers.Authorization =
      `Bearer ${accessToken}`
  }

  return config
}, undefined)

// Request interceptor error capture
//@ts-ignore
axiosInstance.interceptors.request.use(undefined, (error: Error) => {})

// Response result interceptor processing
axiosInstance.interceptors.response.use((res: AxiosResponse<any>) => {
  res && axiosCanceler.removePending(res.config)
  return res
}, undefined)

// Response result interceptor error capture
axiosInstance.interceptors.response.use(undefined, (error) => {
  const { response, code, message, config } = error || {}
  const msg: string = response?.data?.error?.message ?? ''
  const err: string = error?.toString?.() ?? ''
  let errMessage = ''

  try {
    if (code === 'ECONNABORTED' && message.indexOf('timeout') !== -1) {
      errMessage = '接口请求超时,请刷新页面重试!'
    }
    if (err?.includes('Network Error')) {
      errMessage = '网络异常，请检查您的网络连接是否正常!'
    }

    if (errMessage) {
      Modal.error({ title: '错误提示', content: errMessage })
      return Promise.reject(error)
    }
  } catch (error) {
    throw new Error(error as unknown as string)
  }

  checkStatus(error?.response?.status, msg)

  // 添加自动重试机制 保险起见 只针对GET请求
  const retryRequest = new AxiosRetry()
  const isOpenRetry = true
  config.method?.toUpperCase() === RequestEnum.GET &&
    isOpenRetry &&
    // @ts-ignore
    retryRequest.retry(axiosInstance, error)
  return Promise.reject(error)
})

export default axiosInstance
